import Cookies from 'js-cookie'
import { decrypt, encrypt } from './jsencrypt'

const tokenKey = 'auth-token'

export function getToken() {
  let token = Cookies.get(tokenKey)
  token = token ? JSON.parse(token) : undefined
  // console.log('getToken', token)
  return token
}

export function setToken(token) {
  // console.log('setToken', token)
  const tokenData = JSON.stringify(token)
  return Cookies.set(tokenKey, tokenData)
}

export function removeToken() {
  return Cookies.remove(tokenKey)
}

export function setRememberMeInfo(info) {
  // console.log('设置Cookie', info)
  Cookies.set('username', info['username'], { expires: 30 })
  if (info['password']) {
    Cookies.set('password', encrypt(info['password']), { expires: 30 })
  }
  Cookies.set('rememberMe', info['rememberMe'], { expires: 30 })
}

export function getRememberMeInfo() {
  const username = Cookies.get('username')
  let password = Cookies.get('password')
  const rememberMe = Cookies.get('rememberMe')
  if (password) {
    password = decrypt(password)
  }
  // console.log('获取Cookie', info)
  return {
    username,
    password,
    rememberMe
  }
}

export function removeRememberMeInfo() {
  // console.log('删除Cookie')
  Cookies.remove('username')
  Cookies.remove('password')
  Cookies.remove('rememberMe')
}

